package com.truyentranh.requester;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.truyentranh.data.AdsDataObject;
import com.truyentranh.data.HaiBLMetalData;
import com.truyentranh.data.HaiBLModule;
import com.truyentranh.data.NewsDataObject;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.network.UrlHelper;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.Logger;

public class NewsRequester extends Request{
	
	private RequestListener requestListener;	
	
	public NewsRequester(RequestListener listener){
		this.requestListener = listener;
	}
	
	@Override
	public void cancelRequest() {
		// TODO Auto-generated method stub		
	}

	@Override
	public void runRequest() {
		// TODO Auto-generated method stub
		url = UrlHelper.getUrlOfRequestUpdates(UrlHelper.BASE_URL_NEWS_ALL);
		send();
	}	
	
	private ArrayList<NewsDataObject> arrayList = new ArrayList<NewsDataObject>();
	private boolean myself = false;
	
	public boolean isMySelf(){
		return this.myself;
	}
	
	@Override
	public void requestFinished(JSONObject jsonObject) {
		
		if(jsonObject != null){
			try {
				if(jsonObject.has("data")){
					JSONArray array = jsonObject.getJSONArray("data");
					if(array != null){
						for(int i = 0 , n = array.length() ; i<n;i++){
							JSONObject childAds = array.getJSONObject(i);
							
							int id = childAds.has("id") ? childAds.getInt("id") : -1;					
							String name =childAds.has("name") ? childAds.getString("name") : "";
							String icon = childAds.has("icon") ?  childAds.getString("icon") : "";
							
							NewsDataObject adsDataObject = new NewsDataObject(id, name,  icon);
							arrayList.add(adsDataObject);
						}
					}					
				}	
				myself = jsonObject.has("self") ? (jsonObject.getInt("self") == 1 ? true : false) : false;
				
				if(requestListener != null){
					requestListener.onRequestComplete(this);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void requestFailed(int errorCode, String message) {
		// TODO Auto-generated method stub
		if(requestListener != null){
			requestListener.onRequestFailed(message, this);
		}
	}

	/**
	 * @return the arrayList
	 */
	public ArrayList<NewsDataObject> getArrayList() {
		return arrayList;
	}
}
